package com.manner.groupon.service.groupon.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manner.groupon.common.BaseResponse;
import com.manner.groupon.common.PageResult;
import com.manner.groupon.common.ResultUtils;
import com.manner.groupon.mapper.*;
import com.manner.groupon.model.dto.order.AdminOrderDTO;
import com.manner.groupon.model.dto.search.OrderSearch;
import com.manner.groupon.model.entity.*;
import com.manner.groupon.model.vo.*;
import com.manner.groupon.service.groupon.GrouponCouponsService;
import com.manner.groupon.service.groupon.GrouponOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author manner
 * @description 针对表[tb_groupon_order(团购订单表)]的数据库操作Service实现
 * @createDate 2024-10-13 14:26:25
 */
@Service
@RequiredArgsConstructor
public class GrouponOrderServiceImpl extends ServiceImpl<GrouponOrderMapper, GrouponOrder>
        implements GrouponOrderService {

    private final GrouponOrderMapper grouponOrderMapper;

    private final GrouponCouponsService grouponCouponsService;

    private final StoreMapper storeMapper;

    private final GroupPurchasePackageMapper groupPurchasePackageMapper;

    private final StoreLinkManMapper storeLinkManMapper;

    private final UserMapper userMapper;


    @Override
    public BaseResponse<PageResult<CouponOrderVo>> search(OrderSearch search) {
        //构建分页对象
        IPage<GrouponOrder> page = new Page<>(search.getCurrent(), search.getPageSize());
        //构建查询对象
        QueryWrapper<GrouponOrder> wrapper = new QueryWrapper<GrouponOrder>().eq("user_id", search.getUser());
        //判断
        if (search.getStatus() != 0) {
            wrapper.eq("status", search.getStatus());
        }
        //排序
        wrapper.orderByDesc("create_time");
        //查询数据
        IPage<GrouponOrder> result = grouponOrderMapper.selectPage(page, wrapper);
        //准备容器
        List<CouponOrderVo> list = new ArrayList<>();
        //查询订单团购券数据
        result.getRecords().forEach(item -> {
            GrouponCoupons value = grouponCouponsService.query().eq("id", item.getGcId()).one();
            //添加进入容器
            list.add(new CouponOrderVo(item, value, null, null, null));
        });
        //返回数据
        return ResultUtils.success(new PageResult<>(list, result.getTotal()));
    }

    @Override
    public BaseResponse<PageResult<CouponOrderVo>> query_list(String orderNo, String phone, int current, int pageSize, int status, String userPhone) {
        //获取用户信息
        StoreLinkMan linkMan = storeLinkManMapper.selectOne(new QueryWrapper<StoreLinkMan>().eq("phone", phone));
        //获取该用户手机号的门店
        List<Store> list = storeMapper.selectList(new QueryWrapper<Store>().eq("admin_id", linkMan.getId()));
        //转为ID集合
        List<String> collect = list.stream().map(Store::getStoreNo).collect(Collectors.toList());


        //构建查询条件
        QueryWrapper<GrouponOrder> wrapper = new QueryWrapper<GrouponOrder>().in("store_no", collect);
        //判读
        if (!StrUtil.isBlank(orderNo)) {
            wrapper.eq("groupon_order_id", orderNo);
        }
        if (status != 0) {
            wrapper.eq("status", status);
        }
        wrapper.orderByDesc("create_time");
        //判断
        if (StrUtil.isNotBlank(userPhone)) {
            //获取用户手机号
            User one = userMapper.selectOne(new QueryWrapper<User>().eq("phone", userPhone));
            //判断
            if (ObjectUtil.isNull(one)) {
                return ResultUtils.success(new PageResult<>(Collections.emptyList(), 0));
            }
            wrapper.eq("user_id", one.getId());
        }
        //构建分页对象
        IPage<GrouponOrder> page = new Page<>(current, pageSize);
        //分页查询
        IPage<GrouponOrder> result = grouponOrderMapper.selectPage(page, wrapper);
        //准备容器
        List<CouponOrderVo> container = new ArrayList<>();
        //遍历
        result.getRecords().forEach(item -> {
            GrouponCoupons value = grouponCouponsService.query().eq("id", item.getGcId()).one();
            //查询套餐项内容
            List<GroupPurchasePackage> packages = groupPurchasePackageMapper.selectList(new QueryWrapper<GroupPurchasePackage>().eq("gcid", value.getId()));
            //准备容器
            List<GroupCouponPackageVo> items = new ArrayList<>();
            packages.forEach(pack -> {
                //转换
                JSONArray jsonArray = JSONUtil.parseArray(pack.getGpContent());
                List<CouponItem> couponItems = JSONUtil.toList(jsonArray, CouponItem.class);
                //添加数据
                items.add(new GroupCouponPackageVo(pack.getGpTitle(), couponItems));
            });
            //获取用户数据
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", item.getUserId()));
            //添加进入容器
            container.add(new CouponOrderVo(item, value,
                    list.stream().filter(store -> store.getStoreNo().equals(item.getStoreNo())).findFirst().get(),
                    items, user.getPhone()));
        });
        //返回数据
        return ResultUtils.success(new PageResult<>(container, result.getTotal()));
    }

    @Override
    public BaseResponse<OrderDetailVo> query_no(String no) {
        //查询订单数据
        GrouponOrder order = query().eq("groupon_order_id", no).one();
        //查询团购券数据
        GrouponCoupons coupon = grouponCouponsService.query().eq("id", order.getGcId()).one();
        //查询团购套餐信息
        List<GroupPurchasePackage> packages = groupPurchasePackageMapper.selectList(new QueryWrapper<GroupPurchasePackage>().eq("gcid", coupon.getId()));
        //准备容器
        List<GroupCouponPackageVo> container = new ArrayList<>();
        //转换数据
        packages.forEach(item -> {
            List<CouponItem> items = JSONUtil.toList(item.getGpContent(), CouponItem.class);
            //添加进入容器
            container.add(new GroupCouponPackageVo(item.getGpTitle(), items));
        });
        //获取门店数据
        Store store = storeMapper.selectOne(new QueryWrapper<Store>().eq("store_no", coupon.getStoreId()));
        //获取门店联系人信息
        StoreLinkMan linkMan = storeLinkManMapper.selectOne(new QueryWrapper<StoreLinkMan>().eq("id", store.getAdminId()));
        //获取用户手机号
        String phone = userMapper.selectOne(new QueryWrapper<User>().eq("id", order.getUserId())).getPhone();
        //返回数据
        return ResultUtils.success(new OrderDetailVo(order, store, linkMan, coupon, container, phone));
    }

    @Override
    public BaseResponse<PageResult<AdminOrderVO>> query_search(AdminOrderDTO adminOrderDTO) {
        //构建分页对象
        Page<GrouponOrder> page = new Page<>(adminOrderDTO.getCurrent(), adminOrderDTO.getPageSize());
        //构建查询对象
        QueryWrapper<GrouponOrder> wrapper = new QueryWrapper<>();
        //判断
        if (adminOrderDTO.getStatus() != 0) {
            wrapper.eq("status", adminOrderDTO.getStatus());
        }
        if (adminOrderDTO.getStartTime() != null && adminOrderDTO.getEndTime() != null && adminOrderDTO.getStartTime() != "" && adminOrderDTO.getEndTime() != "") {
            wrapper.between("create_time", adminOrderDTO.getStartTime(), adminOrderDTO.getEndTime());
        }
        if (adminOrderDTO.getOrderNo() != null && adminOrderDTO.getOrderNo() != "") {
            wrapper.eq("groupon_order_id", adminOrderDTO.getOrderNo());
        }
        wrapper.orderByDesc("create_time");
        //查询数据
        Page<GrouponOrder> result = grouponOrderMapper.selectPage(page, wrapper);
        //准备容器
        List<AdminOrderVO> container = new ArrayList<>();
        //转换
        result.getRecords().forEach(item -> {
            //查询团购券数据
            GrouponCoupons one = grouponCouponsService.query().eq("id", item.getGcId()).one();
            //查询用户数据
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", item.getUserId()));
            //添加进入容器
            container.add(new AdminOrderVO(item.getId(), item.getGrouponOrderId(), item.getPayId(), item.getStoreNo(), item.getGcId(), item.getUserId(),
                    item.getDeductionCouponId(), item.getPaymentMethod(), item.getTicketNumber(), item.getTotalAmount(), item.getStatus(),
                    item.getCreateTime(), item.getUpdateTime(), one.getTitle(), one.getImg(), one.getPrice(), user.getPhone()));
        });
        //返回数据
        return ResultUtils.success(new PageResult<>(container, result.getTotal()));
    }
}




